<template>
<div>
  <el-card class="search-card">
    <BasicForm
      ref="formData"
      :formColumns="formItemList"
      :dataSource="formData"
      :defaultExpandStatus="false"
      :handleSearchForm="handleQueryForm"
      :colNumOfRow="4"
      @getFormData="getFormData"
    ></BasicForm>
  </el-card>
  <el-card class="table-card">
    <basic-table
      showActionCol
      showSelectCol
      :loading="tableInfo.loading"
      :columns="tableInfo.columns"
      :dataSource="tableInfo.list"
      :pagination="pagination"
      :tableHeight="460"
      :actionColWidth="150"
      :selectionChange="handleSelectionChange"
      :actionRender="renderTableBtnAction"
      @pageChange="handlePageChange"
      @pageSizeChange="handlePageSizeChange"
    >
      <el-row type="flex" slot="content_context">
        <el-button
          v-if="showBtn('导出') && supplierExportConfig.supplier"
          :loading="exportLoading"
          size="mini"
          type="primary"
          @click="handleExport"
          >导出</el-button
        >
        <el-button
          v-if="showBtn('下载资质')"
          type="primary"
          :loading="btnLoading.batchDownload"
          :disabled="this.tableInfo.selection.length == 0"
          @click="handleBatchDownload"
        >批量下载</el-button>
      </el-row>
    </basic-table>
  </el-card>
</div>
</template>
<script>
import { getBtnsId } from '@/libs/btnsPermission';
import BasicPage from '@/mixins/supplier/basicPage';
import Dict from '@/mixins/supplier/dict';
import BasicForm from '@/components/supplier/BasicForm';
import BasicTable from '@/components/supplier/BasicTable';
import { FORM_ITEM_LIST, TABLE_COLUMNS } from './constants';
import { getTableAction } from '@/pages/supplier/utils/btnsUtils';
import { isResponseSuccess } from '@/pages/supplier/utils/bizUtils';
import { createAttachmentByExport, createExcelByExport } from '@/utils/bizUtils';
import {
  querySupplierQualificationListService,
  downloadSupplierQualificationService,
  previewSupplierQualificationService,
  exportSupplierQualificationService
} from '@/api/supplier/management/supplierQualification';
export default {
  mixins: [BasicPage, Dict],
  components: {
    BasicForm,
    BasicTable
  },
  data () {
    return {
      exportLoading: false,
      formItemList: FORM_ITEM_LIST,
      formData: {
        qualification: '', // 资质名称
        supplierCode: '', // 供应商编码
        supplierName: '', // 供应商名称
        mainCategoryId: '', // 主营品类
        supplierNature: '', // 供应商性质
        createUser: '', // 上传人
        validTime: [], // 资质有效期
        managementAreaId: '', // 管理区域
        belongDepartment: '', // 归属中心
        cooperativeBrandId: '', // 合作品牌
        uploadTime: [], // 上传时间
        updateTime: [], // 更新时间
      },
      tableInfo: {
        list: [],
        columns: TABLE_COLUMNS,
        loading: false,
        selection: []
      },
      btnLoading: {
        batchDownload: false
      }
    }
  },
  computed: {
    // 表单入参
    formParams () {
      const [startTime = '', endTime = ''] = this.formData['validTime'];
      const [uploadStartTime = '', uploadEndTime = ''] = this.formData['uploadTime'];
      const [updateStartTime = '', updateEndTime = ''] = this.formData['updateTime'];
      let params = {
        ...this.formData,
        startTime,
        endTime,
        updateStartTime,
        updateEndTime,
        uploadStartTime,
        uploadEndTime,
      };
      delete params.validTime;
      return params;
    }
  },
  mounted () {
    this.handleQueryForm();
  },
  methods: {
    renderTableBtnAction (h, { row }) {
      const actionList = [
        { label: '查看', method: this.handleView, hasAuth: true },
        { label: '下载资质', method: this.handleDownloadQualification, hasAuth: true }
      ];
      return getTableAction({ h, row, actionList, showBtn: this.showBtn });
    },
    // 导出
    async handleExport () {
      const res = await exportSupplierQualificationService(this.formParams, state => { this.exportLoading = state })
      if (res) {
        createExcelByExport({ excelTitle: '供应商资质管理', res })
      }
    },
    // 批量下载
    handleBatchDownload () {
      const urls = this.tableInfo.selection.map(item => item.annex);
      this.downloadQualifications(urls, state => { this.tableInfo.loading = state; });
    },
    // 查看
    handleView (row) {
      sessionStorage.setItem('buttonId', getBtnsId('查看'));
      this.previewFile(row.annex);
    },
    // 下载资质
    handleDownloadQualification (row) {
      this.downloadQualifications([row.annex], (state) => { this.tableInfo.loading = state; });
    },
    // 表格勾选
    handleSelectionChange (selection) {
      this.tableInfo.selection = selection;
    },
    // 资质下载请求
    async downloadQualifications (urls, loadingFn) {
      sessionStorage.setItem('buttonId', getBtnsId('下载资质'));
      loadingFn(true);
      const res = await downloadSupplierQualificationService({ urls });
      loadingFn(false);
      createAttachmentByExport({ res, title: '资质信息', type: 'zip' });
    },
    // 预览附件
    async previewFile (annex) {
      const res = await previewSupplierQualificationService({ annex });
      if (isResponseSuccess(res)) {
        window.open(res.result);
      }
    },
    // 获取表单数据
    getFormData (formData) {
      this.formData = formData;
    },
    // 获取表单查询入参
    getParamsBySearchForm () {
      const { current, size } = this.pagination;
      return { ...this.formParams, current, size };
    },
    // 获取表格数据
    async getTableData () {
      sessionStorage.setItem('buttonId', getBtnsId('查询'));
      this.tableInfo.loading = true;
      const res = await querySupplierQualificationListService(this.getParamsBySearchForm());
      this.tableInfo.loading = false;
      if (isResponseSuccess(res)) {
        this.tableInfo.list = res.result?.records || [];
        this.pagination.total = res.result.total;
      }
    },
  }
}
</script>
